<template>
  <div class="geade" v-loading="loading" element-loading-text="加载中...">
    <div class="header">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="addType"> 添加分类</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">批量启用</el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">批量禁用</el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">批量删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model="typeInput"
          placeholder="名称搜索"
          class="input-with mr5"
          clearable
          @keyup.enter="getTypeData"
          @clear="getTypeData"
        />
        <HButton type="primary" @click="getTypeData">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table">
      <el-table
        border
        stripe
        resizable
        :data="typeList"
        @selection-change="handleChange"
        ref="typeTable"
        height="100%"
        style="position: absolute"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column type="index" label="序号" width="65" />
        <el-table-column show-overflow-tooltip prop="name" label="分类名称" />
        <!-- <el-table-column
          show-overflow-tooltip
          prop="knowledgeType"
          label="分配知识库类型权限名称"
        /> -->
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="scope.row.status === false">启用</HStatus>
            <HStatus v-if="scope.row.status === true" type="info">禁用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink @click="viewTypeDetail(scope.row)">编辑</HLink>
              <!-- <HLink @click="onShowUpgrade">分配知识库类型权限</HLink> -->
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <Pagination
        ref="typePaginDom"
        :list_total="typeTotal"
        @size-change="getTypeData"
        @current-change="getTypeData"
      />
    </div>
  </div>

  <!-- 添加/编辑  分类弹窗 -->
  <HModal v-model="addDialog" size="small">
    <template #header>
      <div class="my-header">
        <h3 class="title">{{ typeForm.title }}</h3>
      </div>
    </template>
    <div v-loading="typeLoading" element-loading-text="加载中...">
      <div class="form-text">
        <el-form
          label-width="80"
          ref="typeFormRef"
          :rules="typeRules"
          :model="typeForm"
          class="form_content"
          @validate="handleFormValidate"
        >
          <el-form-item
            label="分类名称"
            :class="{ form_item: formValidateResult, validate_fail: !formValidateResult }"
            prop="name"
          >
            <el-input
              v-model="typeForm.name"
              class="item-input"
              clearable
              placeholder="请输入名称"
            />
          </el-form-item>
          <el-form-item label="分类状态" class="form-item">
            <el-radio-group v-model="typeForm.status" class="el-group">
              <el-radio :value="false">
                <span class="bg_text">启用</span>
              </el-radio>
              <el-radio :value="true">
                <span class="bg_text">禁用</span>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footerLeft>
      <HPlainBgButton
        is-modal
        type="error"
        v-show="typeForm.title == '编辑分类'"
        @click="changeStatus(4)"
        >删除</HPlainBgButton
      >
    </template>

    <template #footerRight>
      <HButton is-modal type="primary" @click="saveType(typeFormRef)">保存</HButton>
      <HButton is-modal @click="onClose">取消</HButton>
    </template>
  </HModal>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, onMounted, reactive, markRaw, h } from 'vue'
  import { Search, Warning, Delete, ArrowDown } from '@element-plus/icons-vue'
  import { ElDivider, ElMessage, ElMessageBox, FormItemProp } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { getTypeList, saveUserType, changeType, deleteType } from '@/api/users'
  import { Category } from './types'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import { HModal } from '@/components/common'

  /**
   * 显示升级维护事件
   */
  const onShowUpgrade = () => {
    ElMessage({
      type: 'success',
      message: '正在升级维护中，敬请期待...',
    })
  }

  /**
   * 表单验证结果
   */
  const formValidateResult = ref(true)

  /**
   * 表单验证事件
   */
  const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
    formValidateResult.value = isValid
  }

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    addDialog.value = false
    formValidateResult.value = true
  }

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 用户分类数据
  const typeForm = reactive({
    id: null,
    name: '',
    status: false,
    title: '',
  })

  const typeLoading = ref(false)
  const typeList = ref<Array<Category>>([]) // 列表数据
  const typeTable = ref() // 列表dom
  const typeInput = ref('') // 搜索框
  const typePaginDom = ref() // 分页dom
  const typeTotal = ref() // 总数目
  const typeFormRef = ref<FormInstance>() // 表单元素

  const typeRules = reactive({
    name: [{ required: true, message: '请输入分类名称', trigger: ['blur', 'change'] }],
  })

  const loading = ref(false)
  const addDialog = ref(false)

  const props = defineProps({
    active_name: String,
  })

  onMounted(() => {
    if (props.active_name == 'type') {
      getTypeData()
    }
  })

  // 获取分类列表
  const getTypeData = async () => {
    loading.value = true
    const data = {
      limit: typePaginDom.value.size,
      name: typeInput.value,
      page: typePaginDom.value.current,
      status: '',
    }
    const res = await getTypeList(data)
    typeList.value = res.data.data.rows
    typeTotal.value = parseInt(res.data.data.total)
    loading.value = false
  }

  // 添加分类
  const addType = () => {
    typeForm.title = '添加分类'
    typeForm.status = false
    typeForm.name = ''
    addDialog.value = true
  }

  // 修改分类
  const viewTypeDetail = (obj: Category) => {
    typeForm.title = '编辑分类'
    typeForm.status = obj.status
    typeForm.name = obj.name
    typeForm.id = obj.id
    addDialog.value = true
  }

  // 封装保存数据的方法
  const saveDataMethod = (method, data, dialog, getData, load) => {
    load.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        dialog.value = false
        load.value = false
        getData()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        load.value = false
        return
      }
    })
  }

  // 保存分类数据
  const saveType = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    const data = {
      id: typeForm.id,
      name: typeForm.name,
      status: typeForm.status,
    }
    formEl.validate((valid) => {
      if (valid) {
        if (typeForm.title == '添加分类') {
          saveDataMethod(saveUserType, data, addDialog, getTypeData, typeLoading)
        } else {
          saveDataMethod(saveUserType, data, addDialog, getTypeData, typeLoading)
        }
      }
    })
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: Array<Category>) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 封装修改状态的方法
  const changeDisable = (type: string, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的分类`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的分类?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        const res = await method(arr, status)
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
      } else {
        const res = await method(arr)
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        if (dialog == 1) {
          addDialog.value = false
        }
      }
      selecttion.value = []
      typeTable.value.clearSelection()
      getTypeData()
    })
  }

  // 批量启用/禁用
  const changeStatus = (param: 1 | 2 | 3 | 4) => {
    if (param === 1) {
      changeDisable('启用', changeType, selecttion.value, false, '')
    }
    if (param === 2) {
      changeDisable('禁用', changeType, selecttion.value, true, '')
    }
    if (param === 3) {
      changeDisable('删除', deleteType, selecttion.value, 3, '')
    }
    if (param === 4) {
      changeDisable('删除', deleteType, [typeForm.id], 3, 1)
    }
  }

  defineExpose({ getTypeData })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
  @import './UserType.scss';
</style>
